package com.example.nationmobile;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.entity.mime.MultipartEntity;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.coe3.data.Information;
import com.coe3.datahandler.BaseActivity;
import com.coe3.datahandler.HttpConnection;
import com.coe3.datahandler.ParserXMLHandler;
import com.coe3.datahandler.ParserXMLHandler.ElementData;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class OpinionActivity extends BaseActivity implements OnClickListener,OnItemClickListener{

	
	private TextView txt_daytime;
	private FrameLayout Img_home,Img_opinion,Img_mul,Img_favorite,Img_setting; 
	
	//==================ListView======================
	private ListView lstView;
	private OpiListAdapter adapter;
	private ArrayList<HashMap<String, Object>> MyArrList_home;
	private HashMap<String, Object> map_1 = new HashMap<String, Object>();
	private	ProgressDialog mProgressDialog;
	private String URL="http://www.nationmultimedia.com/new/rss/ipad_v2/opinion_top.xml";
	private View list_mul;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		
		//Control.current_tab=24;// Opinion
		
		Log.e("evt", "====================onCreate====================");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_opinion);
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//==============Tab=====================
		Img_home=(FrameLayout)findViewById(R.id.Img_home);
		Img_opinion=(FrameLayout)findViewById(R.id.Img_opinion);
		Img_mul=(FrameLayout)findViewById(R.id.Img_mul);
		Img_favorite=(FrameLayout)findViewById(R.id.Img_favorite);
		Img_setting =(FrameLayout)findViewById(R.id.Img_setting);
		
		Img_home.setOnClickListener(this);
		//img_opinion.setOnClickListener(this);
		Img_mul.setOnClickListener(this);
		Img_favorite.setOnClickListener(this);
		Img_setting .setOnClickListener(this);
		
		
		
		
		
		
		if (lstView == null) {
			lstView = (ListView) findViewById(R.id.list_view);
			setProgressBarIndeterminateVisibility(true);
			lstView.setOnItemClickListener(this);
			 //=====================ProgressDialog==========================
	        mProgressDialog = new ProgressDialog(this);
	        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
	        mProgressDialog.setMessage("Loading......");                       
	        mProgressDialog.setCancelable(false);  
	        
	        
	      
	        
			
		}
		if (MyArrList_home == null)
			MyArrList_home = new ArrayList<HashMap<String, Object>>();
		
		SetTime();
		
		
		//if(Control.List_title_Opinoin.size()<1)
		startConnection(URL, "", HttpConnection.GET, -1, null );
		//else{
			
			
		//Add_DataTolist();
			
		//}
		
		
		
	}

	
	
 	private void SetTime()
	{
		
	    String resultTxt=""+DateFormat.format("MM/dd/yy , h:mmaa", System.currentTimeMillis());
		txt_daytime=(TextView)findViewById(R.id.txt_daytime);
		txt_daytime.setText(resultTxt);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v.getId()==R.id.Img_home)
		{
			finish();	
			overridePendingTransition (R.anim.fade_in, R.anim.fade_out);
		}
		
		if(v.getId()==R.id.Img_mul)
		{
			finish();	
			startActivityForResult(new Intent(OpinionActivity.this,MulActivity.class), 0);
			overridePendingTransition (R.anim.fade_in, R.anim.fade_out);
		}
		
		if(v.getId()==R.id.Img_favorite)
		{
			finish();	
			startActivityForResult(new Intent(OpinionActivity.this,FavoritesActivity.class), 0);
			overridePendingTransition (R.anim.fade_in, R.anim.fade_out);
		}
		if(v.getId()==R.id.Img_setting)
		{
			finish();	
			startActivityForResult(new Intent(OpinionActivity.this,SettingActivity.class), 0);
			overridePendingTransition (R.anim.fade_in, R.anim.fade_out);
		}
		
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		// TODO Auto-generated method stub
		Log.e("NT", "position_list="+position+"");
		Control.news_description=Control.List_description_Opinoin.get(position);
		Control.news_detail=Control.List_detail_Opinoin.get(position);
		Control.news_photo=Control.List_photo_Opinoin.get(position);
		Control.news_title=Control.List_title_Opinoin.get(position);
		startActivity(new Intent(OpinionActivity.this,NewsDetailActivity.class));
		
	}
	
	
	
	
	
	
	
	//===========================Parser===============================
		@SuppressLint("HandlerLeak")
		public void startConnection( String url, String data , int method, final int handlerType, final MultipartEntity entity ) {
				Log.e("max", "MainActivity==========startConnection");
				Log.e("chud", "url: " + url);
				Log.e("chud", "data: " + data);
				
				Handler handler = new Handler() {
					@SuppressWarnings("deprecation")
					public void handleMessage(Message message) {
						switch ( message.what ) {
						case HttpConnection.DID_START:
								showDialog( DIALOG_CONNECTION_START );
							break;
						
						case HttpConnection.DID_SUCCEED:
							try {
								Log.e("chud", "(String)message.obj: " + (String)message.obj);
								startParseXMLResponse( (String)message.obj, handlerType );
								didFinishParsing();
								
							} catch ( Exception e ) {
								Log.e( "Connection Exception", "XML Pasing Excpetion : " + e );
				        		didFinishParsing();
							}
							
							break;
						
						case HttpConnection.DID_ERROR:
							Log.e( "Connection Error", "HTTP Connection did error : " + message.obj );
			        		
			        		didFinishParsing();
							break;
						}	
					}
				};

				HttpConnection connection = new HttpConnection(handler);
				if( entity != null )
					connection.setMultipartEntity( entity );
				connection.create(method, url, data);
			}

		public void startParseXMLResponse( String response, int handlerType ) throws SAXException, ParserConfigurationException, IOException {
				
				Log.e("max", "MainActivity==========startParseXMLResponse");
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				
				ParserXMLHandler parser = null;
				Handler handler = handlerInformation(handlerType);
				parser = new ParserXMLHandler( this, handler );
				
				StringReader sr = new StringReader(response);
				InputSource is = new InputSource(sr);
				
				xr.setContentHandler(parser);
				xr.parse(is);
			}
			
		private static Vector<NewData> mListNews = new Vector<NewData>();
		private NewData mItem = null;
		@SuppressLint("HandlerLeak")
		public Handler handlerInformation(final int handlerType) {
				
				Log.e("max", "MainActivity==========handlerInformation");
				
				Handler mHandler = new Handler() {
					public void handleMessage( Message message ) {
						ElementData data = ( ElementData )message.obj;
						switch( message.what ) {
							case ParserXMLHandler.START_DOCUMENT:
								
								mListNews.removeAllElements();
								
								break;
								
							case ParserXMLHandler.DID_START_ELEMENT:
								
								if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
								{
									mItem = new NewData();
								}//end if
								
							
								
								
								break;
								
							case ParserXMLHandler.DID_FINISH_ELEMENT:
								
								if( data.name.equalsIgnoreCase(NewData.TAG_TITLE) ) 
								{
									mItem.title = Information.setData(data.value, Information.STR_EMPTY);
								} 
								
								if( data.name.equalsIgnoreCase(NewData.TAG_DESCRIPTION) ) 
								{
									mItem.description = Information.setData(data.value, Information.STR_EMPTY);
								} 
								
								if( data.name.equalsIgnoreCase(NewData.TAG_DETAIL) ) 
								{
									mItem.detail = Information.setData(data.value, Information.STR_EMPTY);
								} 
								
								else if( data.name.equalsIgnoreCase(NewData.TAG_THUMB) ) 
								{
									mItem.thumbnail = Information.setData(data.value, Information.STR_EMPTY);
								}
								
								else if( data.name.equalsIgnoreCase(NewData.TAG_PHOTO) ) 
								{
									mItem.photo = Information.setData(data.value, Information.STR_EMPTY);
								}
								
								else if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
								{
									mListNews.add(mItem);
									mItem = null;
								}//end if
								
								break;
								
							case ParserXMLHandler.END_DOCUMENT:
								
								setNews(mListNews);
							   
								break;
						}
					}
				};
					
				return mHandler;
			}
		public void setNews(Vector<NewData> listNews) {
				
				
				if (adapter == null) {
					adapter = new OpiListAdapter(OpinionActivity.this, MyArrList_home);
					lstView.setAdapter(adapter);
				}
				
				
				
				for (NewData newData : listNews) {
					
					map_1 = new HashMap<String, Object>();
					
					Log.e("max","enclosure_url="+ newData.title);
					Log.e("max","enclosure_url="+ newData.description);
					Log.e("max","enclosure_url="+ newData.thumbnail);
				
					map_1.put("title", newData.title);
					map_1.put("description", newData.description);
					map_1.put("thumbnail", newData.thumbnail);
					map_1.put("detail", newData.detail);
					map_1.put("photo", newData.photo);
					
					
					Control.List_title_Opinoin.add(newData.title);
					Control.List_description_Opinoin.add(newData.description);
					Control.List_thumbnail_Opinoin.add(newData.thumbnail);
					Control.List_detail_Opinoin.add(newData.detail);
					Control.List_photo_Opinoin.add(newData.photo);
					
					MyArrList_home.add(map_1);	
						

					runOnUiThread (new Thread(new Runnable() { 
				         public void run() {
				                adapter.notifyDataSetChanged();    
				               
				         }
				     }));
					 
					 

					
				
				
			}
			
		}
		

		private void Add_DataTolist()
		{
			
			
			if (adapter == null) {
				adapter = new OpiListAdapter(OpinionActivity.this, MyArrList_home);
				lstView.setAdapter(adapter);
			}
			
			
			
			int i=0;
			while(i<Control.List_title_Opinoin.size())
			{
				
				map_1 = new HashMap<String, Object>();
				map_1.put("title",Control.List_title_Opinoin.get(i));
				map_1.put("description", Control.List_description_Opinoin.get(i));
				map_1.put("thumbnail", Control.List_thumbnail_Opinoin.get(i));
				map_1.put("detail",Control.List_detail_Opinoin.get(i));
				map_1.put("photo",Control.List_photo_Opinoin.get(i));
				MyArrList_home.add(map_1);	
				i++;
				
			}
			
			
			runOnUiThread (new Thread(new Runnable() { 
				public void run() {
				adapter.notifyDataSetChanged();        
				}
			}));
			
			
			
		}
	
		
		
		
		
	 
}
